package com.xunmall.message.service;

import com.xunmall.base.entity.MessageVo;
import com.xunmall.base.exception.BadRequestException;
import com.xunmall.base.exception.BaseException;
import com.xunmall.base.util.RegExpValidatorUtils;
import com.xunmall.message.dto.MessagesForm;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * @Author: WangYanjing
 * @Date: 2019/1/2 11:10
 * @Description:
 */
public class MessagesValidate {
    private static Validator validator;

    public static void Validate(MessagesForm messagesForm) {
        MessageVo messages = new MessageVo();
        if (validator == null) {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            validator = factory.getValidator();
        }
        Set<ConstraintViolation<MessagesForm>> constraintViolations = validator.validate(messagesForm);
        if (constraintViolations.size() > 0) {
            constraintViolations.stream().forEach(
                    item -> messages.addMessageObj(BaseException.ERR_9999, item.getMessage(), item.getPropertyPath().toString())
            );
        }
        if (StringUtils.isNotEmpty(messagesForm.getAddress()) && !RegExpValidatorUtils.isMobile(messagesForm.getAddress())) {
            messages.addMessageObj(BaseException.ERR_9999, "手机格式错误", "");
        }
        if (messages.getReasons().size() > 0) {
            throw new BadRequestException(messages, "");
        }
    }
}
